home *** CD-ROM | disk | FTP | other *** search
/ Programming Sound Cards / Programming Sound Cards.iso / sound_20 / midifile.c < prev    next >
C/C++ Source or Header  |  1995-01-01  |  19KB  |  874 lines

  1. /*
  2.  * midifile 1.11
  3.  * 
  4.  * Read and write a MIDI file.  Externally-assigned function pointers are 
  5.  * called upon recognizing things in the file.
  6.  *
  7.  * Original release ?
  8.  * June 1989 - Added writing capability, M. Czeiszperger.
  9.  *
  10.  *          The file format implemented here is called
  11.  *          Standard MIDI Files, and is part of the Musical
  12.  *          instrument Digital Interface specification.
  13.  *          The spec is avaiable from:
  14.  *
  15.  *               International MIDI Association
  16.  *               5316 West 57th Street
  17.  *               Los Angeles, CA 90056
  18.  *
  19.  *          An in-depth description of the spec can also be found
  20.  *          in the article "Introducing Standard MIDI Files", published
  21.  *          in Electronic Musician magazine, April, 1989.
  22.  * 
  23.  */
  24. #include "midifile.h"
  25. #define NULLFUNC 0
  26. #define NULL 0
  27.  
  28. #define THINK
  29.  
  30. #ifdef THINK
  31. #include <stdlib.h>
  32. #endif
  33.  
  34. #include <stdio.h>
  35.  
  36. char *strcpy(), *strcat();
  37. void exit(), free();
  38.  
  39. /* public stuff */
  40.  
  41. /* Functions to be called while processing the MIDI file. */
  42. int (*Mf_getc)() = NULLFUNC;
  43. int (*Mf_error)() = NULLFUNC;
  44. int (*Mf_header)() = NULLFUNC;
  45. int (*Mf_trackstart)() = NULLFUNC;
  46. int (*Mf_trackend)() = NULLFUNC;
  47. int (*Mf_noteon)() = NULLFUNC;
  48. int (*Mf_noteoff)() = NULLFUNC;
  49. int (*Mf_pressure)() = NULLFUNC;
  50. int (*Mf_parameter)() = NULLFUNC;
  51. int (*Mf_pitchbend)() = NULLFUNC;
  52. int (*Mf_program)() = NULLFUNC;
  53. int (*Mf_chanpressure)() = NULLFUNC;
  54. int (*Mf_sysex)() = NULLFUNC;
  55. int (*Mf_arbitrary)() = NULLFUNC;
  56. int (*Mf_metamisc)() = NULLFUNC;
  57. int (*Mf_seqnum)() = NULLFUNC;
  58. int (*Mf_eot)() = NULLFUNC;
  59. int (*Mf_smpte)() = NULLFUNC;
  60. int (*Mf_tempo)() = NULLFUNC;
  61. int (*Mf_timesig)() = NULLFUNC;
  62. int (*Mf_keysig)() = NULLFUNC;
  63. int (*Mf_seqspecific)() = NULLFUNC;
  64. int (*Mf_text)() = NULLFUNC;
  65.  
  66. /* Functions to implement in order to write a MIDI file */
  67. int (*Mf_putc)() = NULLFUNC;
  68. int (*Mf_writetrack)() = NULLFUNC;
  69. int (*Mf_writetempotrack)() = NULLFUNC;
  70.  
  71. int Mf_nomerge = 0;        /* 1 => continue'ed system exclusives are */
  72.                             /* not collapsed. */
  73. long Mf_currtime = 0L;        /* current time in delta-time units */
  74.  
  75. /* private stuff */
  76. static long Mf_toberead = 0L;
  77. static long Mf_numbyteswritten = 0L;
  78.  
  79. static long readvarinum();
  80. static long read32bit();
  81. static long to32bit();
  82. static int read16bit();
  83. static int to16bit();
  84. static char *msg();
  85.  
  86. mfread()         /* The only non-static function in this file. */
  87. {
  88.     if ( Mf_getc == NULLFUNC )
  89.         mferror("mfread() called without setting Mf_getc"); 
  90.  
  91.     readheader();
  92.     while ( readtrack() )
  93.         ;
  94. }
  95.  
  96. /* for backward compatibility with the original lib */
  97. midifile()
  98. {
  99.     mfread();
  100. }
  101.  
  102. static
  103. readmt(s)        /* read through the "MThd" or "MTrk" header string */
  104. char *s;
  105. {
  106.     int n = 0;
  107.     char *p = s;
  108.     int c;
  109.  
  110.     while ( n++<4 && (c=(*Mf_getc)()) != EOF ) {
  111.         if ( c != *p++ ) {
  112.             char buff[32];
  113.             (void) strcpy(buff,"expecting ");
  114.             (void) strcat(buff,s);
  115.             mferror(buff);
  116.         }
  117.     }
  118.     return(c);
  119. }
  120.  
  121. static
  122. egetc()            /* read a single character and abort on EOF */
  123. {
  124.     int c = (*Mf_getc)();
  125.  
  126.     if ( c == EOF )
  127.         mferror("premature EOF");
  128.     Mf_toberead--;
  129.     return(c);
  130. }
  131.  
  132. static
  133. readheader()        /* read a header chunk */
  134. {
  135.     int format, ntrks, division;
  136.  
  137.     if ( readmt("MThd") == EOF )
  138.         return;
  139.  
  140.     Mf_toberead = read32bit();
  141.     format = read16bit();
  142.     ntrks = read16bit();
  143.     division = read16bit();
  144.  
  145.     if ( Mf_header )
  146.         (*Mf_header)(format,ntrks,division);
  147.  
  148.     /* flush any extra stuff, in case the length of header is not 6 */
  149.     while ( Mf_toberead > 0 )
  150.         (void) egetc();
  151. }
  152.  
  153. static
  154. readtrack()         /* read a track chunk */
  155. {
  156.     /* This array is indexed by the high half of a status byte.  It's */
  157.     /* value is either the number of bytes needed (1 or 2) for a channel */
  158.     /* message, or 0 (meaning it's not  a channel message). */
  159.     static int chantype[] = {
  160.         0, 0, 0, 0, 0, 0, 0, 0,        /* 0x00 through 0x70 */
  161.         2, 2, 2, 2, 1, 1, 2, 0        /* 0x80 through 0xf0 */
  162.     };
  163.     long lookfor;
  164.     int c, c1, type;
  165.     int sysexcontinue = 0;    /* 1 if last message was an unfinished sysex */
  166.     int running = 0;    /* 1 when running status used */
  167.     int status = 0;        /* status value (e.g. 0x90==note-on) */
  168.     int needed;
  169.  
  170.     if ( readmt("MTrk") == EOF )
  171.         return(0);
  172.  
  173.     Mf_toberead = read32bit();
  174.     Mf_currtime = 0;
  175.  
  176.     if ( Mf_trackstart )
  177.         (*Mf_trackstart)();
  178.  
  179.     while ( Mf_toberead > 0 ) {
  180.  
  181.         Mf_currtime += readvarinum();    /* delta time */
  182.  
  183.         c = egetc();
  184.  
  185.         if ( sysexcontinue && c != 0xf7 )
  186.             mferror("didn't find expected continuation of a sysex");
  187.  
  188.         if ( (c & 0x80) == 0 ) {     /* running status? */
  189.             if ( status == 0 )
  190.                 mferror("unexpected running status");
  191.             running = 1;
  192.         }
  193.         else {
  194.             status = c;
  195.             running = 0;
  196.         }
  197.  
  198.         needed = chantype[ (status>>4) & 0xf ];
  199.  
  200.         if ( needed ) {        /* ie. is it a channel message? */
  201.  
  202.             if ( running )
  203.                 c1 = c;
  204.             else
  205.                 c1 = egetc();
  206.             chanmessage( status, c1, (needed>1) ? egetc() : 0 );
  207.             continue;;
  208.         }
  209.  
  210.         switch ( c ) {
  211.  
  212.         case 0xff:            /* meta event */
  213.  
  214.             type = egetc();
  215.             lookfor = Mf_toberead - readvarinum();
  216.             msginit();
  217.  
  218.             while ( Mf_toberead > lookfor )
  219.                 msgadd(egetc());
  220.  
  221.             metaevent(type);
  222.             break;
  223.  
  224.         case 0xf0:        /* start of system exclusive */
  225.  
  226.             lookfor = Mf_toberead - readvarinum();
  227.             msginit();
  228.             msgadd(0xf0);
  229.  
  230.             while ( Mf_toberead > lookfor )
  231.                 msgadd(c=egetc());
  232.  
  233.             if ( c==0xf7 || Mf_nomerge==0 )
  234.                 sysex();
  235.             else
  236.                 sysexcontinue = 1;  /* merge into next msg */
  237.             break;
  238.  
  239.         case 0xf7:    /* sysex continuation or arbitrary stuff */
  240.  
  241.             lookfor = Mf_toberead - readvarinum();
  242.  
  243.             if ( ! sysexcontinue )
  244.                 msginit();
  245.  
  246.             while ( Mf_toberead > lookfor )
  247.                 msgadd(c=egetc());
  248.  
  249.             if ( ! sysexcontinue ) {
  250.                 if ( Mf_arbitrary )
  251.                     (*Mf_arbitrary)(msgleng(),msg());
  252.             }
  253.             else if ( c == 0xf7 ) {
  254.                 sysex();
  255.                 sysexcontinue = 0;
  256.             }
  257.             break;
  258.         default:
  259.             badbyte(c);
  260.             break;
  261.         }
  262.     }
  263.     if ( Mf_trackend )
  264.         (*Mf_trackend)();
  265.     return(1);
  266. }
  267.  
  268. static
  269. badbyte(c)
  270. int c;
  271. {
  272.     char buff[32];
  273.  
  274.     (void) sprintf(buff,"unexpected byte: 0x%02x",c);
  275.     mferror(buff);
  276. }
  277.  
  278. static
  279. metaevent(type)
  280. {
  281.     int leng = msgleng();
  282.     char *m = msg();
  283.  
  284.     switch  ( type ) {
  285.     case 0x00:
  286.         if ( Mf_seqnum )
  287.             (*Mf_seqnum)(to16bit(m[0],m[1]));
  288.         break;
  289.     case 0x01:    /* Text event */
  290.     case 0x02:    /* Copyright notice */
  291.     case 0x03:    /* Sequence/Track name */
  292.     case 0x04:    /* Instrument name */
  293.     case 0x05:    /* Lyric */
  294.     case 0x06:    /* Marker */
  295.     case 0x07:    /* Cue point */
  296.     case 0x08:
  297.     case 0x09:
  298.     case 0x0a:
  299.     case 0x0b:
  300.     case 0x0c:
  301.     case 0x0d:
  302.     case 0x0e:
  303.     case 0x0f:
  304.         /* These are all text events */
  305.         if ( Mf_text )
  306.             (*Mf_text)(type,leng,m);
  307.         break;
  308.     case 0x2f:    /* End of Track */
  309.         if ( Mf_eot )
  310.             (*Mf_eot)();
  311.         break;
  312.     case 0x51:    /* Set tempo */
  313.         if ( Mf_tempo )
  314.             (*Mf_tempo)(to32bit(0,m[0],m[1],m[2]));
  315.         break;
  316.     case 0x54:
  317.         if ( Mf_smpte )
  318.             (*Mf_smpte)(m[0],m[1],m[2],m[3],m[4]);
  319.         break;
  320.     case 0x58:
  321.         if ( Mf_timesig )
  322.             (*Mf_timesig)(m[0],m[1],m[2],m[3]);
  323.         break;
  324.     case 0x59:
  325.         if ( Mf_keysig )
  326.             (*Mf_keysig)(m[0],m[1]);
  327.         break;
  328.     case 0x7f:
  329.         if ( Mf_seqspecific )
  330.             (*Mf_seqspecific)(leng,m);
  331.         break;
  332.     default:
  333.         if ( Mf_metamisc )
  334.             (*Mf_metamisc)(type,leng,m);
  335.     }
  336. }
  337.  
  338. static
  339. sysex()
  340. {
  341.     if ( Mf_sysex )
  342.         (*Mf_sysex)(msgleng(),msg());
  343. }
  344.  
  345. static
  346. chanmessage(status,c1,c2)
  347. int status;
  348. int c1, c2;
  349. {
  350.     int chan = status & 0xf;
  351.  
  352.     switch ( status & 0xf0 ) {
  353.     case 0x80:
  354.         if ( Mf_noteoff )
  355.             (*Mf_noteoff)(chan,c1,c2);
  356.         break;
  357.     case 0x90:
  358.         if ( Mf_noteon )
  359.             (*Mf_noteon)(chan,c1,c2);
  360.         break;
  361.     case 0xa0:
  362.         if ( Mf_pressure )
  363.             (*Mf_pressure)(chan,c1,c2);
  364.         break;
  365.     case 0xb0:
  366.         if ( Mf_parameter )
  367.             (*Mf_parameter)(chan,c1,c2);
  368.         break;
  369.     case 0xe0:
  370.         if ( Mf_pitchbend )
  371.             (*Mf_pitchbend)(chan,c1,c2);
  372.         break;
  373.     case 0xc0:
  374.         if ( Mf_program )
  375.             (*Mf_program)(chan,c1);
  376.         break;
  377.     case 0xd0:
  378.         if ( Mf_chanpressure )
  379.             (*Mf_chanpressure)(chan,c1);
  380.         break;
  381.     }
  382. }
  383.  
  384. /* readvarinum - read a varying-length number, and return the */
  385. /* number of characters it took. */
  386.  
  387. static long
  388. readvarinum()
  389. {
  390.     long value;
  391.     int c;
  392.  
  393.     c = egetc();
  394.     value = c;
  395.     if ( c & 0x80 ) {
  396.         value &= 0x7f;
  397.         do {
  398.             c = egetc();
  399.             value = (value << 7) + (c & 0x7f);
  400.         } while (c & 0x80);
  401.     }
  402.     return (value);
  403. }
  404.  
  405. static long
  406. to32bit(c1,c2,c3,c4)
  407. {
  408.     long value = 0L;
  409.  
  410.     value = (c1 & 0xff);
  411.     value = (value<<8) + (c2 & 0xff);
  412.     value = (value<<8) + (c3 & 0xff);
  413.     value = (value<<8) + (c4 & 0xff);
  414.     return (value);
  415. }
  416.  
  417. static
  418. to16bit(c1,c2)
  419. int c1, c2;
  420. {
  421.     return ((c1 & 0xff ) << 8) + (c2 & 0xff);
  422. }
  423.  
  424. static long
  425. read32bit()
  426. {
  427.     int c1, c2, c3, c4;
  428.  
  429.     c1 = egetc();
  430.     c2 = egetc();
  431.     c3 = egetc();
  432.     c4 = egetc();
  433.     return to32bit(c1,c2,c3,c4);
  434. }
  435.  
  436. static
  437. read16bit()
  438. {
  439.     int c1, c2;
  440.     c1 = egetc();
  441.     c2 = egetc();
  442.     return to16bit(c1,c2);
  443. }
  444.  
  445. /* static */
  446. mferror(s)
  447. char *s;
  448. {
  449.     if ( Mf_error )
  450.         (*Mf_error)(s);
  451.     exit(1);
  452. }
  453.  
  454. /* The code below allows collection of a system exclusive message of */
  455. /* arbitrary length.  The Msgbuff is expanded as necessary.  The only */
  456. /* visible data/routines are msginit(), msgadd(), msg(), msgleng(). */
  457.  
  458. #define MSGINCREMENT 128
  459. static char *Msgbuff = NULL;    /* message buffer */
  460. static int Msgsize = 0;        /* Size of currently allocated Msg */
  461. static int Msgindex = 0;    /* index of next available location in Msg */
  462.  
  463. static
  464. msginit()
  465. {
  466.     Msgindex = 0;
  467. }
  468.  
  469. static char *
  470. msg()
  471. {
  472.     return(Msgbuff);
  473. }
  474.  
  475. static
  476. msgleng()
  477. {
  478.     return(Msgindex);
  479. }
  480.  
  481. static
  482. msgadd(c)
  483. int c;
  484. {
  485.     /* If necessary, allocate larger message buffer. */
  486.     if ( Msgindex >= Msgsize )
  487.         biggermsg();
  488.     Msgbuff[Msgindex++] = c;
  489. }
  490.  
  491. static
  492. biggermsg()
  493. {
  494. /*     char *malloc(); */
  495.     char *newmess;
  496.     char *oldmess = Msgbuff;
  497.     int oldleng = Msgsize;
  498.  
  499.     Msgsize += MSGINCREMENT;
  500.     newmess = (char *) malloc( (unsigned)(sizeof(char)*Msgsize) );
  501.  
  502.     if(newmess == NULL)
  503.         mferror("malloc error!");
  504.         
  505.     /* copy old message into larger new one */
  506.     if ( oldmess != NULL ) {
  507.         register char *p = newmess;
  508.         register char *q = oldmess;
  509.         register char *endq = &oldmess[oldleng];
  510.  
  511.         for ( ; q!=endq ; p++,q++ )
  512.             *p = *q;
  513.         free(oldmess);
  514.     }
  515.     Msgbuff = newmess;
  516. }
  517.  
  518. /*
  519.  * mfwrite() - The only fuction you'll need to call to write out
  520.  *             a midi file.
  521.  *
  522.  * format      0 - Single multi-channel track
  523.  *             1 - Multiple simultaneous tracks
  524.  *             2 - One or more sequentially independent
  525.  *                 single track patterns                
  526.  * ntracks     The number of tracks in the file.
  527.  * division    This is kind of tricky, it can represent two
  528.  *             things, depending on whether it is positive or negative
  529.  *             (bit 15 set or not).  If  bit  15  of division  is zero,
  530.  *             bits 14 through 0 represent the number of delta-time
  531.  *             "ticks" which make up a quarter note.  If bit  15 of
  532.  *             division  is  a one, delta-times in a file correspond to
  533.  *             subdivisions of a second similiar to  SMPTE  and  MIDI
  534.  *             time code.  In  this format bits 14 through 8 contain
  535.  *             one of four values - 24, -25, -29, or -30,
  536.  *             corresponding  to  the  four standard  SMPTE and MIDI
  537.  *             time code frame per second formats, where  -29
  538.  *             represents  30  drop  frame.   The  second  byte
  539.  *             consisting  of  bits 7 through 0 corresponds the the
  540.  *             resolution within a frame.  Refer the Standard MIDI
  541.  *             Files 1.0 spec for more details.
  542.  * fp          This should be the open file pointer to the file you
  543.  *             want to write.  It will have be a global in order
  544.  *             to work with Mf_putc.  
  545.  */ 
  546. void 
  547. mfwrite(format,ntracks,division,fp) 
  548. int format,ntracks,division; 
  549. FILE *fp; 
  550. {
  551.     int i; void mf_write_track_chunk(), mf_write_header_chunk();
  552.  
  553.     if ( Mf_putc == NULLFUNC )
  554.         mferror("mfmf_write() called without setting Mf_putc");
  555.  
  556.     if ( Mf_writetrack == NULLFUNC )
  557.         mferror("mfmf_write() called without setting Mf_mf_writetrack"); 
  558.  
  559.     /* every MIDI file starts with a header */
  560.     mf_write_header_chunk(format,ntracks,division);
  561.  
  562.     /* In format 1 files, the first track is a tempo map */
  563.     if(format == 1 && ( Mf_writetempotrack ))
  564.     {
  565.     (*Mf_writetempotrack)();
  566.     }
  567.  
  568.     /* The rest of the file is a series of tracks */
  569.     for(i = 0; i < ntracks; i++)
  570.         mf_write_track_chunk(i,fp);
  571. }
  572.  
  573. void 
  574. mf_write_track_chunk(which_track,fp)
  575. int which_track;
  576. FILE *fp;
  577. {
  578.     unsigned long trkhdr,trklength;
  579.     long offset, place_marker;
  580.     void write16bit(),write32bit();
  581.     
  582.     
  583.     trkhdr = MTrk;
  584.     trklength = 0;
  585.  
  586.     /* Remember where the length was written, because we don't
  587.        know how long it will be until we've finished writing */
  588.     offset = ftell(fp); 
  589.  
  590. #ifdef DEBUG
  591.         printf("offset = %d\n",(int) offset);
  592. #endif
  593.  
  594.     /* Write the track chunk header */
  595.     write32bit(trkhdr);
  596.     write32bit(trklength);
  597.  
  598.     Mf_numbyteswritten = 0L; /* the header's length doesn't count */
  599.  
  600.     if( Mf_writetrack )
  601.     {
  602.         (*Mf_writetrack)(which_track);
  603.     }
  604.  
  605.     /* mf_write End of track meta event */
  606.     eputc(0);
  607.     eputc(meta_event);
  608.     eputc(end_of_track);
  609.  
  610.      eputc(0);
  611.      
  612.     /* It's impossible to know how long the track chunk will be beforehand,
  613.            so the position of the track length data is kept so that it can
  614.            be written after the chunk has been generated */
  615.     place_marker = ftell(fp);
  616.     
  617.     /* This method turned out not to be portable because the
  618.            parameter returned from ftell is not guaranteed to be
  619.            in bytes on every machine */
  620.      /* track.length = place_marker - offset - (long) sizeof(track); */
  621.  
  622. #ifdef DEBUG
  623. printf("length = %d\n",(int) trklength);
  624. #endif
  625.  
  626.      if(fseek(fp,offset,0) < 0)
  627.         mferror("error seeking during final stage of write");
  628.  
  629.     trklength = Mf_numbyteswritten;
  630.  
  631.     /* Re-mf_write the track chunk header with right length */
  632.     write32bit(trkhdr);
  633.     write32bit(trklength);
  634.  
  635.     fseek(fp,place_marker,0);
  636. } /* End gen_track_chunk() */
  637.  
  638.  
  639. void 
  640. mf_write_header_chunk(format,ntracks,division)
  641. int format,ntracks,division;
  642. {
  643.     unsigned long ident,length;
  644.     void write16bit(),write32bit();
  645.     
  646.     ident = MThd;           /* Head chunk identifier                    */
  647.     length = 6;             /* Chunk length                             */
  648.  
  649.     /* individual bytes of the header must be written separately
  650.        to preserve byte order across cpu types :-( */
  651.     write32bit(ident);
  652.     write32bit(length);
  653.     write16bit(format);
  654.     write16bit(ntracks);
  655.     write16bit(division);
  656. } /* end gen_header_chunk() */
  657.  
  658.  
  659. /*
  660.  * mf_write_midi_event()
  661.  * 
  662.  * Library routine to mf_write a single MIDI track event in the standard MIDI
  663.  * file format. The format is:
  664.  *
  665.  *                    <delta-time><event>
  666.  *
  667.  * In this case, event can be any multi-byte midi message, such as
  668.  * "note on", "note off", etc.      
  669.  *
  670.  * delta_time - the time in ticks since the last event.
  671.  * type - the type of meta event.
  672.  * chan - The midi channel.
  673.  * data - A pointer to a block of chars containing the META EVENT,
  674.  *        data.
  675.  * size - The length of the meta-event data.
  676.  */
  677. int 
  678. mf_write_midi_event(delta_time, type, chan, data, size)
  679. unsigned long delta_time;
  680. unsigned int chan,type;
  681. unsigned long size;
  682. unsigned char *data;
  683. {
  684.     int i;
  685.     void WriteVarLen();
  686.     unsigned char c;
  687.  
  688.     WriteVarLen(delta_time);
  689.  
  690.     /* all MIDI events start with the type in the first four bits,
  691.        and the channel in the lower four bits */
  692.     c = type | chan;
  693.  
  694.     if(chan > 15)
  695.         perror("error: MIDI channel greater than 16\n");
  696.  
  697.     eputc(c);
  698.  
  699.     /* write out the data bytes */
  700.     for(i = 0; i < size; i++)
  701.     eputc(data[i]);
  702.  
  703.     return(size);
  704. } /* end mf_write MIDI event */
  705.  
  706. /*
  707.  * mf_write_meta_event()
  708.  *
  709.  * Library routine to mf_write a single meta event in the standard MIDI
  710.  * file format. The format of a meta event is:
  711.  *
  712.  *          <delta-time><FF><type><length><bytes>
  713.  *
  714.  * delta_time - the time in ticks since the last event.
  715.  * type - the type of meta event.
  716.  * data - A pointer to a block of chars containing the META EVENT,
  717.  *        data.
  718.  * size - The length of the meta-event data.
  719.  */
  720. int
  721. mf_write_meta_event(delta_time, type, data, size)
  722. unsigned long delta_time;
  723. unsigned char *data,type;
  724. unsigned long size;
  725. {
  726.     int i;
  727.  
  728.     WriteVarLen(delta_time);
  729.     
  730.     /* This marks the fact we're writing a meta-event */
  731.     eputc(meta_event);
  732.  
  733.     /* The type of meta event */
  734.     eputc(type);
  735.  
  736.     /* The length of the data bytes to follow */
  737.     WriteVarLen(size); 
  738.  
  739.     for(i = 0; i < size; i++)
  740.     {
  741.     if(eputc(data[i]) != data[i])
  742.         return(-1); 
  743.     }
  744.     return(size);
  745. } /* end mf_write_meta_event */
  746.  
  747. void 
  748. mf_write_tempo(tempo)
  749. unsigned long tempo;
  750. {
  751.     /* Write tempo */
  752.     /* all tempos are written as 120 beats/minute, */
  753.     /* expressed in microseconds/quarter note     */
  754.     eputc(0);
  755.     eputc(meta_event);
  756.     eputc(set_tempo);
  757.  
  758.     eputc(3);
  759.     eputc((unsigned)(0xff & (tempo >> 16)));
  760.     eputc((unsigned)(0xff & (tempo >> 8)));
  761.     eputc((unsigned)(0xff & tempo));
  762. }
  763.  
  764. unsigned long 
  765. mf_sec2ticks(secs,division,tempo)
  766. int division;
  767. unsigned int tempo;
  768. float secs;
  769. {    
  770.      return (long)(((secs * 1000.0) / 4.0 * division) / tempo);
  771. }
  772.  
  773. /*
  774.  * Write multi-length bytes to MIDI format files
  775.  */
  776. void 
  777. WriteVarLen(value)
  778. unsigned long value;
  779. {
  780.   unsigned long buffer;
  781.  
  782.   buffer = value & 0x7f;
  783.   while((value >>= 7) > 0)
  784.   {
  785.     buffer <<= 8;
  786.     buffer |= 0x80;
  787.     buffer += (value & 0x7f);
  788.   }
  789.   while(1){
  790.        eputc((unsigned)(buffer & 0xff));
  791.        
  792.     if(buffer & 0x80)
  793.         buffer >>= 8;
  794.     else
  795.         return;
  796.     }
  797. }/* end of WriteVarLen */
  798.  
  799. /* 
  800.  * This routine converts delta times in ticks into seconds. The
  801.  * else statement is needed because the formula is different for tracks
  802.  * based on notes and tracks based on SMPTE times.
  803.  *
  804.  */
  805. float 
  806. mf_ticks2sec(ticks,division,tempo)
  807. int division;
  808. unsigned int tempo;
  809. unsigned long ticks;
  810. {
  811.     float smpte_format, smpte_resolution;
  812.  
  813.     if(division > 0)
  814.         return ((float) (((float)(ticks) * (float)(tempo)) / ((float)(division) * 1000000.0)));
  815.     else
  816.     {
  817.        smpte_format = upperbyte(division);
  818.        smpte_resolution = lowerbyte(division);
  819.        return (float) ((float) ticks / (smpte_format * smpte_resolution * 1000000.0));
  820.     }
  821. } /* end of ticks2sec() */
  822.  
  823.  
  824. /*
  825.  * write32bit()
  826.  * write16bit()
  827.  *
  828.  * These routines are used to make sure that the byte order of
  829.  * the various data types remains constant between machines. This
  830.  * helps make sure that the code will be portable from one system
  831.  * to the next.  It is slightly dangerous that it assumes that longs
  832.  * have at least 32 bits and ints have at least 16 bits, but this
  833.  * has been true at least on PCs, UNIX machines, and Macintosh's.
  834.  *
  835.  */
  836. void 
  837. write32bit(data)
  838. unsigned long data;
  839. {
  840.     eputc((unsigned)((data >> 24) & 0xff));
  841.     eputc((unsigned)((data >> 16) & 0xff));
  842.     eputc((unsigned)((data >> 8 ) & 0xff));
  843.     eputc((unsigned)(data & 0xff));
  844. }
  845.  
  846. void 
  847. write16bit(data)
  848. int data;
  849. {
  850.     eputc((unsigned)((data & 0xff00) >> 8));
  851.     eputc((unsigned)(data & 0xff));
  852. }
  853.  
  854. /* write a single character and abort on error */
  855. eputc(c)            
  856. unsigned char c;
  857. {
  858.     int return_val;
  859.     
  860.     if((Mf_putc) == NULLFUNC)
  861.     {
  862.         mferror("Mf_putc undefined");
  863.         return(-1);
  864.     }
  865.     
  866.     return_val = (Mf_putc)(c);
  867.  
  868.     if ( return_val == EOF )
  869.         mferror("error writing");
  870.         
  871.     Mf_numbyteswritten++;
  872.     return(return_val);
  873. }
  874.